package com.google.code.cisx.client;

import com.google.code.cisx.client.DesktopEvent.DesktopEventType;
import com.google.code.cisx.client.event.EventManager;
import com.google.code.cisx.client.gadgets.CommonListGadget;
import com.google.code.cisx.client.gadgets.LoginGadget;
import com.google.code.cisx.client.gadgets.ProjectListGadget;
import com.google.code.cisx.client.model.GadgetClass;
import com.google.code.cisx.client.view.DesktopView;
import com.google.code.cisx.client.view.DesktopViewListener;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;

public class Desktop implements EntryPoint, DesktopViewListener, DesktopEventListener<DesktopEvent> {
  public static final String LAYOUT_ROOT_ELT = "DesktopView";
  Storage storage;
  DesktopView view;

  public void onModuleLoad() {
    // add gadgets
    // GadgetClass.addClass(new HelloWorldGadget.Class());
    // GadgetClass.addClass(new CalendarGadget.Class());
    // GadgetClass.addClass(new ToDoListGadget.Class());
    // GadgetClass.addClass(new GoogleMapsGadget.Class());
    // GadgetClass.addClass(new WeatherGadget.Class());
    // GadgetClass.addClass(new NewsGadget.Class());
    // GadgetClass.addClass(new DiceWarsGadget.Class());
    GadgetClass.addClass(new LoginGadget.Class());
    GadgetClass.addClass(new ProjectListGadget.Class());
    GadgetClass.addClass(new CommonListGadget.Class());

    EventManager.getInstance().addEventListener(DesktopEventType.DESKTOP_STATE_CHANGED.toString(),
        this);

    // create view
    view = new DesktopView(this);
    RootPanel.get(LAYOUT_ROOT_ELT).add(view);

    /* --Not using Google Gears-- */
    // load layout from storage
    // if( GearsStorage.isGearsInstalled() )
    // storage = new GearsStorage();
    // else
    storage = new CookieStorage();
    String layout = storage.getValue("layout");
    if (layout != null)
      view.setLayoutFromString(layout);
  }

  public void onInterfaceChange() {
    // save layout to storage
    String layout = view.getLayoutAsString();
    storage.setValue("layout", layout);
    try {
      storage.save();
    } catch (StorageException e) {
      Window.alert("unable to save the desktops state");
    }
  }

  /**
   * {@inheritDoc}
   * 
   * @see com.google.code.cisx.client.event.TypedEventListener#onEvent(com.google.code.cisx.client.event.TypedEvent)
   */
  public void onEvent(DesktopEvent event) {
    if (event.getType().equals(DesktopEventType.DESKTOP_STATE_CHANGED.toString()))
      handleDesktopStateChanged(event);
  }

  private void handleDesktopStateChanged(DesktopEvent event) {
    onInterfaceChange();
  }
}
